#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os

import yaml

from backend.app.common.log import log
from backend.app.core.path_conf import YamlPath


class DoYaml(object):
    """ 操作yaml文件 """

    def __init__(self, path=YamlPath, filename='...'):
        # 默认文件: conf.yaml
        self.filename = os.path.join(path, filename)

    def read_yaml(self):
        """ 获取yaml值 """
        try:
            if self.filename:
                log.info('正在读取yaml文件 {}'.format(self.filename))
                with open(self.filename, encoding='utf-8') as f:
                    return yaml.load(f.read(), Loader=yaml.FullLoader)
        except FileNotFoundError as e:
            log.error('您调用的yaml文件不存在')
            log.error(e)
            return {'error': '您调用的yaml文件不存在'}

    def write_yaml(self, data):
        """ 写入yaml值 """
        try:
            if self.filename:
                log.info('正在写入yaml文件 {}'.format(self.filename))
                with open(self.filename, encoding='utf-8', mode='w') as f:
                    return yaml.dump(data, stream=f, allow_unicode=True)
        except FileNotFoundError as e:
            log.error('您调用的yaml文件不存在')
            log.error(e)
            return {'error': '您调用的yaml文件不存在'}


if __name__ == '__main__':
    ry = DoYaml(filename='???').read_yaml()
    print(json.dumps(ry, indent=4, ensure_ascii=False, separators=(',', ':')))
